import express, { Request } from 'express'
import https from 'node:https'
import fs from 'node:fs'
import path from 'node:path'
import EventEmitter from 'node:events'

const app = express()

// 加载SSL证书
const sslOptions = {
  key: fs.readFileSync(path.resolve('D:/OpenSSL', 'private-key.pem')),
  cert: fs.readFileSync(path.resolve('D:/OpenSSL', 'certificate.pem')),
}

app.use(express.static(import.meta.dirname))
app.use(express.json()) // 解析 JSON 数据
app.use(express.urlencoded({ extended: true })) // 解析 URL-encoded 数据

const sseClients = new Map<
  string,
  {
    req: Request
    timerId?: ReturnType<typeof setInterval>
  }
>()
type SSEEvent = {
  type?: string
  data?: any
  id?: string
  retry?: number
}
app.get('/api/sse', (req: Request<{}, any, any, { uuid: string }, Record<string, any>>, res) => {
  res.setHeader('Content-Type', 'text/event-stream')
  res.setHeader('Cache-Control', 'no-cache')
  res.setHeader('Connection', 'keep-alive')

  req.socket.setTimeout(60000)
  req.socket.setKeepAlive(true)

  // 添加连接状态检查
  const isConnectionAlive = () => req.socket.writable && !res.writableEnded && !req.destroyed
  // 清理关闭的 client
  const removeClient = (clientId: string) => {
    const client = sseClients.get(clientId)
    client?.timerId && clearInterval(client.timerId)
    sseClients.delete(clientId)
  }

  req.on('sse', ({ type = 'message', data = {}, id, retry }: SSEEvent) => {
    // 检查连接状态
    if (!isConnectionAlive()) {
      console.log('sse:', '连接已关闭，不再发送消息')
      removeClient(clientId)
      return
    }

    res.write(`event: ${type}\n`)
    if (req.headers['last-event-id']) {
      res.write(`id: ${req.headers['last-event-id']}\n`)
    } else if (id) {
      res.write(`id: ${id}\n`)
    }
    if (retry) {
      res.write(`retry: ${retry}\n`)
    }
    res.write(`data: ${JSON.stringify(data)}\n\n`)
  })

  // 添加心跳检测，30s 一次（可选）
  const heartbeatInterval = setInterval(() => {
    if (!isConnectionAlive()) {
      console.log('heartbeat:', '连接已关闭，不再发送消息')
      clearInterval(heartbeatInterval)
      return
    }
    res.write(': this is a comment, just prevent connection timeout\n\n')
  }, 30000)
  req.on('error', (err) => {
    console.log('sse 连接错误', err)
    removeClient(clientId)
    res.end()
  })
  req.on('close', () => {
    console.log('sse 连接关闭')
    removeClient(clientId)
    res.end()
  })

  const clientId = req.query.uuid || (req.headers['access-token'] as string)
  console.log(`Client connected: ${clientId}`)
  if (!sseClients.has(clientId)) {
    // 存储客户端连接和定时器ID
    sseClients.set(clientId, Object.seal({ req, timerId: undefined }))
  }
  res.write(
    `data: ${JSON.stringify({
      type: 'welcome',
      data: '欢迎来到 SSE 服务',
    })}\n\n`,
  )
})

const checkClient = (req: Request<{}, any, { uuid: string }>) => {
  const clientId = req.body.uuid || (req.headers['access-token'] as string)
  if (!sseClients.has(clientId)) {
    console.log('Client not found')
    return null
  }
  return sseClients.get(clientId)
}
app.post('/api/startReportCurrentTime', (req, res) => {
  const client = checkClient(req)
  if (!client) {
    res.status(404).send('Client not found')
    return
  }
  client.timerId && clearInterval(client.timerId)
  client.timerId = setInterval(() => {
    if (client) {
      client.req.emit('sse', {
        id: 'server-time',
        type: 'server-time',
        data: {
          'server-time': new Date().toLocaleString(),
        },
      })
    }
  }, 1000)
  res.send('ok')
})
app.post('/api/stopReportCurrentTime', (req, res) => {
  const client = checkClient(req)
  if (!client) {
    res.status(404).send('Client not found')
    return
  }
  client.timerId && clearInterval(client.timerId) && (client.timerId = undefined)
  res.send('ok')
})
app.post('/api/reportCustomEvent', (req: Request<{}, any, { uuid: string; type: string; data: string }>, res) => {
  const client = checkClient(req)
  if (!client) {
    res.status(404).send('Client not found')
    return
  }
  const body = req.body
  client.req.emit('sse', {
    id: Math.floor(Math.random() * 1000).toString(),
    type: body.type,
    data: JSON.parse(body.data),
  })
  res.send('ok')
})

const eventEmitter = new EventEmitter()
eventEmitter.on('sse', (eventData: SSEEvent) => {
  for (const client of sseClients.values()) {
    client.req.emit('sse', eventData)
  }
})
app.post('/api/reportAllClient', (req: Request<{}, any, { uuid: string; type: string; data: string }>, res) => {
  const body = req.body
  eventEmitter.emit('sse', {
    type: body.type,
    data: JSON.parse(body.data),
  })
  res.send('ok')
})

// 创建HTTPS服务器
const server = https.createServer(sslOptions, app)

server.listen(3000, () => {
  console.log('HTTPS 服务启动成功，端口: 3000')
})
